from flask import Blueprint, request, jsonify, current_app
import logging, os
from utils import common
import config, json

role_bp = Blueprint('role', __name__, url_prefix='/role')

@role_bp.route('/list')
def list():
    params = request.args
    if params.get('user_id'):
        result = current_app.config['DB'].list_available_role(params.get('user_id'))
    elif params.get('all'):
        result = current_app.config['DB'].list_all_role()


    return jsonify({"code":0, "data":result})


@role_bp.route('/update', methods=['POST'])
def update():
    params = request.json
    token = request.headers.get('Authorization')
    try:
        result = current_app.config['DB'].update_available_role(params)
        ## 同时更新redis中值
        tmp = current_app.config['REDIS'].get(token)
        value = json.loads(tmp)
        value['chat_roles'] = params.get('keys')
        current_app.config['REDIS'].set(token, json.dumps(value), ex= config.LIFESPAN )
        
        return jsonify({"code":0})
    except Exception as e:
        return jsonify({'code':0, 'msg':str(e)})

@role_bp.record
def log(app):
    logging.info('register role blueprint')
